<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use app\common\tool\Result;
use think\Response;
use think\exception\ValidateException;

class Login extends Base
{
    /**
     * 登录
     * @return Response
     */
    public function check(): Response
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'Login');
            $user = User::where('code', $param['mobile'])->find();
            if (empty($user)) return Result::fail('账号不存在');

            if ($user['password'] != md5($param['password'])) {
                return Result::fail('密码错误');
            }
            if ($user['is_lock'] == 1) {
                return Result::fail('账号已冻结');
            }
            $time = time();
            $token = md5(json_encode($user) . $time . $this->request->ip());
            $user->token = $token;
            $user->last_time = $time;
            $user->last_ip = $this->request->ip();
            $user->save();
            return Result::fastReturn(['code' => 1, 'msg' => '登录成功', 'token' => $token]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 注册
     * @return Response
     */
    public function register(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Register');
            return Result::fastReturn(User::_save($param,''));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
